﻿using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Extensions;
using Abp.Hangfire.Configuration;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Runtime.Caching.Redis;
using Abp.Runtime.Security;
using Abp.Threading.BackgroundWorkers;
using Abp.Timing;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Mt.Site.Application.Auditing;
using Mt.Site.Core.BackGroundJobs;
using Mt.Site.Core.Configuration;
using Mt.Site.Core.MultiTenancy;
using Mt.Site.EntityFrameworkCore;

namespace Mt.Site.Web.Startup
{
    [DependsOn(
        typeof(MtSiteWebCoreModule)
    )]
    public class MtSiteWebModule : AbpModule
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;

        public MtSiteWebModule(
            IWebHostEnvironment env)
        {
            _env = env;
            _appConfiguration = env.GetAppConfiguration();
        }

        public override void PreInitialize()
        {
            //Configuration.Modules.AbpWebCommon().MultiTenancy.DomainFormat =
            //   _appConfiguration["App:ServerRootAddress"] ?? "https://localhost:44301/";

            Clock.Provider = ClockProviders.Local;

            //默认租户的名称
            Tenant.DefaultTenantName = MtSiteConsts2.DefaultTenantName;
            //多租户系统
            Configuration.MultiTenancy.IsEnabled = MtSiteConsts2.MultiTenancyEnabled;

            AbpClaimTypes.TenantId = "TenantId";
            AbpClaimTypes.ImpersonatorUserId = "ImpersonatorUserId";
            AbpClaimTypes.ImpersonatorTenantId = "ImpersonatorTenantId";

            //Changed AntiForgery token/cookie names to not conflict to the main application while redirections.
            //Configuration.Modules.AbpWebCommon().AntiForgery.TokenCookieName = "Public-XSRF-TOKEN";
            //Configuration.Modules.AbpWebCommon().AntiForgery.TokenHeaderName = "Public-X-XSRF-TOKEN";

            var hangfireEnable = _appConfiguration["App:HangfireEnable"];
            if(hangfireEnable =="false")
            {
                Configuration.BackgroundJobs.IsJobExecutionEnabled = false;
            }
            else
            {
                if (MtSiteConsts2.BackgroundJobs)
                {
                    Configuration.BackgroundJobs.UseHangfire();
                }
            }

            //Uncomment this line to use Redis cache instead of in-memory cache.
            //See app.config for Redis configuration and connection string
            var redisCacheEnable = _appConfiguration["RedisCache:IsEnabled"];
            if (redisCacheEnable == "true")
            {
                Configuration.Caching.UseRedis(options =>
                {
                    options.ConnectionString = _appConfiguration["RedisCache:ConnectionString"];
                    options.DatabaseId = _appConfiguration.GetValue<int>("RedisCache:DatabaseId");
                });
            }
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(MtSiteWebModule).GetAssembly());
        }

        public override void PostInitialize()
        {
            using (var scope = IocManager.CreateScope())
            {
                if (!scope.Resolve<DatabaseCheckHelper>()
                    .Exist(_appConfiguration.GetConnectionStringByAutoDecrypt(MtSiteConsts2.ConnectionStringName)))
                {
                    return;
                }
            }

            var workManager = IocManager.Resolve<IBackgroundWorkerManager>();
            if (Configuration.Auditing.IsEnabled && ExpiredAuditLogDeleterWorker.IsEnabled)
            {
                workManager.Add(IocManager.Resolve<ExpiredAuditLogDeleterWorker>());
            }
            if (WorkFlowPeriodicNoticeWorker.IsEnabled)
            {
                workManager.Add(IocManager.Resolve<WorkFlowPeriodicNoticeWorker>());
            }
            //ConfigureExternalAuthProviders();
        }

        //private void ConfigureExternalAuthProviders()
        //{
        //    var externalAuthConfiguration = IocManager.Resolve<ExternalAuthConfiguration>();

        //    if (bool.Parse(_appConfiguration["Authentication:OpenId:IsEnabled"]))
        //    {
        //        if (bool.Parse(_appConfiguration["Authentication:AllowSocialLoginSettingsPerTenant"]))
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                IocManager.Resolve<TenantBasedOpenIdConnectExternalLoginInfoProvider>());
        //        }
        //        else
        //        {
        //            var jsonClaimMappings = new List<JsonClaimMap>();
        //            _appConfiguration.GetSection("Authentication:OpenId:ClaimsMapping").Bind(jsonClaimMappings);

        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                new OpenIdConnectExternalLoginInfoProvider(
        //                    _appConfiguration["Authentication:OpenId:ClientId"],
        //                    _appConfiguration["Authentication:OpenId:ClientSecret"],
        //                    _appConfiguration["Authentication:OpenId:Authority"],
        //                    _appConfiguration["Authentication:OpenId:LoginUrl"],
        //                    bool.Parse(_appConfiguration["Authentication:OpenId:ValidateIssuer"]),
        //                    jsonClaimMappings
        //                )
        //            );
        //        }
        //    }

        //    if (bool.Parse(_appConfiguration["Authentication:WsFederation:IsEnabled"]))
        //    {
        //        if (bool.Parse(_appConfiguration["Authentication:AllowSocialLoginSettingsPerTenant"]))
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                IocManager.Resolve<TenantBasedWsFederationExternalLoginInfoProvider>());
        //        }
        //        else
        //        {
        //            var jsonClaimMappings = new List<JsonClaimMap>();
        //            _appConfiguration.GetSection("Authentication:WsFederation:ClaimsMapping").Bind(jsonClaimMappings);

        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                new WsFederationExternalLoginInfoProvider(
        //                    _appConfiguration["Authentication:WsFederation:ClientId"],
        //                    _appConfiguration["Authentication:WsFederation:Tenant"],
        //                    _appConfiguration["Authentication:WsFederation:MetaDataAddress"],
        //                    _appConfiguration["Authentication:WsFederation:Authority"],
        //                    jsonClaimMappings
        //                )
        //            );
        //        }
        //    }

        //    if (bool.Parse(_appConfiguration["Authentication:Facebook:IsEnabled"]))
        //    {
        //        if (bool.Parse(_appConfiguration["Authentication:AllowSocialLoginSettingsPerTenant"]))
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                IocManager.Resolve<TenantBasedFacebookExternalLoginInfoProvider>());
        //        }
        //        else
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(new FacebookExternalLoginInfoProvider(
        //                _appConfiguration["Authentication:Facebook:AppId"],
        //                _appConfiguration["Authentication:Facebook:AppSecret"]
        //            ));
        //        }
        //    }

        //    if (bool.Parse(_appConfiguration["Authentication:Twitter:IsEnabled"]))
        //    {
        //        if (bool.Parse(_appConfiguration["Authentication:AllowSocialLoginSettingsPerTenant"]))
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                IocManager.Resolve<TenantBasedTwitterExternalLoginInfoProvider>());
        //        }
        //        else
        //        {
        //            var twitterExternalLoginInfoProvider = new TwitterExternalLoginInfoProvider(
        //                _appConfiguration["Authentication:Twitter:ConsumerKey"],
        //                _appConfiguration["Authentication:Twitter:ConsumerSecret"],
        //                _appConfiguration["App:ClientRootAddress"].EnsureEndsWith('/') + "account/login"
        //            );

        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(twitterExternalLoginInfoProvider);
        //        }
        //    }

        //    if (bool.Parse(_appConfiguration["Authentication:Google:IsEnabled"]))
        //    {
        //        if (bool.Parse(_appConfiguration["Authentication:AllowSocialLoginSettingsPerTenant"]))
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                IocManager.Resolve<TenantBasedGoogleExternalLoginInfoProvider>());
        //        }
        //        else
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                new GoogleExternalLoginInfoProvider(
        //                    _appConfiguration["Authentication:Google:ClientId"],
        //                    _appConfiguration["Authentication:Google:ClientSecret"],
        //                    _appConfiguration["Authentication:Google:UserInfoEndpoint"]
        //                )
        //            );
        //        }
        //    }

        //    if (bool.Parse(_appConfiguration["Authentication:Microsoft:IsEnabled"]))
        //    {
        //        if (bool.Parse(_appConfiguration["Authentication:AllowSocialLoginSettingsPerTenant"]))
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                IocManager.Resolve<TenantBasedMicrosoftExternalLoginInfoProvider>());
        //        }
        //        else
        //        {
        //            externalAuthConfiguration.ExternalLoginInfoProviders.Add(
        //                new MicrosoftExternalLoginInfoProvider(
        //                    _appConfiguration["Authentication:Microsoft:ConsumerKey"],
        //                    _appConfiguration["Authentication:Microsoft:ConsumerSecret"]
        //                )
        //            );
        //        }
        //    }
        //}
    }
}
